package com.eng.carro.mb;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import com.eng.carro.entities.User;
import com.eng.carro.services.UserInfo;
import com.eng.carro.services.UserService;

@ManagedBean(name = "userMB")
@RequestScoped
public class UserMBean implements Serializable {

  private static final long serialVersionUID = 6034778587807204396L;

  private User user;

  @EJB
  UserService service;

  public UserMBean() {
  }

  @PostConstruct
  public void init() {
	user = new User();
  }

  public User getUser() {
	return user;
  }

  public void setUser(User user) {
	this.user = user;
  }

  public void entrar() {
	try {
	  User result = service.findByEmailPass(user);

	  if (result != null) {
		if (result.getRole() == 0) {
		  FacesContext.getCurrentInstance().getExternalContext()
			  .redirect("administrator.jsf");
		} else if (result.getRole() == 1) {
		  FacesContext.getCurrentInstance().getExternalContext()
			  .redirect("almox.jsf");
		}
		
		UserInfo.getInstance().setCurrentUser(result);
	  } else {
		addMessage("Login incorreto!", "");
	  }
	} catch (Exception e) {
	  e.printStackTrace();
	}
  }

  public void addMessage(String summary, String detail) {
	FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
		summary, detail);
	FacesContext.getCurrentInstance().addMessage(null, message);
  }
}
